<script lang="tsx" setup>
import {defineEmits, onBeforeUnmount, onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {Download, FullScreen, Setting} from '@element-plus/icons-vue'

/**
 * 定义emit
 */
const emit = defineEmits<{
  (e: 'export'): void
  (e: 'table-config'): void
}>()

/**
 * 定义props
 */
const props = defineProps<{
  extendButton?: extendButton
}>()

/**
 * 全屏
 */
const isFullscreen = ref<boolean>(false)

/**
 * 导出
 */
const handleExport = () => {
  emit('export')
}

/**
 * 表格配置
 */
const handleConfig = () => {
  emit('table-config')
}

/**
 * 处理全屏切换
 */
const handleToggleFullscreen = () => {
  const element = document.querySelector('.fullscreen-element') as HTMLElement

  if (!isFullscreen.value) {
    if (element.requestFullscreen) {
      element.requestFullscreen().catch(err => {
        ElMessage.error('进入全屏失败: ' + err.message)
      })
    } else {
      ElMessage.error('当前浏览器不支持全屏功能')
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else {
      ElMessage.error('当前浏览器不支持退出全屏功能')
    }
  }
}

/**
 * 全屏状态变化处理
 */
const handleFullscreenChange = () => {
  isFullscreen.value = !!(document.fullscreenElement || (document as any).webkitFullscreenElement || (document as any).msFullscreenElement)
  localStorage.setItem('fullscreen', isFullscreen.value.toString())
}

onMounted(() => {
  const savedFullscreen = sessionStorage.getItem('fullscreen')
  isFullscreen.value = savedFullscreen === 'true'
  document.addEventListener('fullscreenchange', handleFullscreenChange)
})

onBeforeUnmount(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
})
</script>

<template>
  <div v-if="extendButton" class="table-program-form">
    <el-button v-if="extendButton.tableConfig" link size="small" @click="handleConfig">
      <el-icon>
        <Setting/>
      </el-icon>
      <span>配置表格</span>
    </el-button>
    <el-button v-if="extendButton.export" link size="small" @click="handleExport">
      <el-icon>
        <Download/>
      </el-icon>
      <span>导出</span>
    </el-button>
    <el-button v-if="extendButton.fullScreen" link size="small" @click="handleToggleFullscreen">
      <el-icon>
        <FullScreen/>
      </el-icon>
      <span>全屏</span>
    </el-button>
  </div>
</template>

<style lang="scss" scoped>
.table-program-form {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;

  :deep(.el-button) {
    box-shadow: none !important;
  }
}
</style>